// 设置搜索组件
// 提供设置项的搜索功能

import React, { useState, useEffect, useMemo } from 'react';
import { Search, X } from 'lucide-react';
import { useSettingsStore } from '../../stores/settingsStore';
import { SettingSearchResult, SettingsCategory } from '../../types/settings';

// 模拟设置项数据（实际应该从设置定义中获取）
const mockSettings = [
  {
    id: 'editor.fontSize',
    name: '字体大小',
    description: '编辑器中代码的字体大小',
    category: SettingsCategory.Editor,
    tags: ['字体', '大小', '编辑器']
  },
  {
    id: 'editor.fontFamily',
    name: '字体系列',
    description: '编辑器使用的字体系列',
    category: SettingsCategory.Editor,
    tags: ['字体', '系列', '编辑器']
  },
  {
    id: 'editor.tabSize',
    name: '制表符大小',
    description: '制表符对应的空格数量',
    category: SettingsCategory.Editor,
    tags: ['制表符', '缩进', '空格']
  },
  {
    id: 'editor.wordWrap',
    name: '自动换行',
    description: '是否启用自动换行',
    category: SettingsCategory.Editor,
    tags: ['换行', '自动', '编辑器']
  },
  {
    id: 'appearance.theme',
    name: '主题',
    description: '应用程序的颜色主题',
    category: SettingsCategory.Appearance,
    tags: ['主题', '颜色', '外观']
  },
  {
    id: 'appearance.accentColor',
    name: '强调色',
    description: '界面的强调色',
    category: SettingsCategory.Appearance,
    tags: ['颜色', '强调', '外观']
  },
  {
    id: 'keyboard.shortcuts',
    name: '快捷键',
    description: '键盘快捷键映射',
    category: SettingsCategory.Keyboard,
    tags: ['快捷键', '键盘', '映射']
  }
];

export const SettingsSearch: React.FC = () => {
  const { searchQuery, searchSettings, clearSearch } = useSettingsStore();
  const [inputValue, setInputValue] = useState(searchQuery);

  // 搜索结果
  const searchResults = useMemo(() => {
    if (!inputValue.trim()) return [];

    const query = inputValue.toLowerCase();
    const results: SettingSearchResult[] = [];

    mockSettings.forEach((setting) => {
      let score = 0;
      let matchType: 'name' | 'description' | 'tag' = 'name';
      let matchText = '';

      // 检查名称匹配
      if (setting.name.toLowerCase().includes(query)) {
        score += 10;
        matchType = 'name';
        matchText = setting.name;
      }

      // 检查描述匹配
      if (setting.description.toLowerCase().includes(query)) {
        score += 5;
        if (matchType !== 'name') {
          matchType = 'description';
          matchText = setting.description;
        }
      }

      // 检查标签匹配
      const matchingTag = setting.tags.find(tag => 
        tag.toLowerCase().includes(query)
      );
      if (matchingTag) {
        score += 3;
        if (matchType !== 'name' && matchType !== 'description') {
          matchType = 'tag';
          matchText = matchingTag;
        }
      }

      // 精确匹配加分
      if (setting.name.toLowerCase() === query) {
        score += 20;
      }

      if (score > 0) {
        results.push({
          setting: {
            id: setting.id,
            name: setting.name,
            description: setting.description,
            category: setting.category,
            type: 'string' as any,
            defaultValue: '',
            currentValue: '',
            tags: setting.tags
          },
          matchType,
          matchText,
          score
        });
      }
    });

    // 按分数排序
    return results.sort((a, b) => b.score - a.score);
  }, [inputValue]);

  // 处理输入变化
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    setInputValue(value);
    
    // 延迟搜索以避免频繁更新
    const timeoutId = setTimeout(() => {
      if (value.trim()) {
        searchSettings(value);
      } else {
        clearSearch();
      }
    }, 300);

    return () => clearTimeout(timeoutId);
  };

  // 清除搜索
  const handleClearSearch = () => {
    setInputValue('');
    clearSearch();
  };

  // 处理搜索结果点击
  const handleResultClick = (result: SettingSearchResult) => {
    // TODO: 跳转到对应的设置项
    console.log('Navigate to setting:', result.setting.id);
  };

  // 高亮匹配文本
  const highlightMatch = (text: string, query: string) => {
    if (!query.trim()) return text;

    const regex = new RegExp(`(${query})`, 'gi');
    const parts = text.split(regex);

    return parts.map((part, index) => 
      regex.test(part) ? (
        <mark key={index} className="bg-yellow-200 dark:bg-yellow-800">
          {part}
        </mark>
      ) : part
    );
  };

  return (
    <div className="relative">
      {/* 搜索输入框 */}
      <div className="relative">
        <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
        <input
          type="text"
          value={inputValue}
          onChange={handleInputChange}
          placeholder="搜索设置..."
          className="w-full pl-10 pr-10 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-white placeholder-gray-500 dark:placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
        />
        {inputValue && (
          <button
            onClick={handleClearSearch}
            className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
          >
            <X className="w-4 h-4" />
          </button>
        )}
      </div>

      {/* 搜索结果 */}
      {inputValue && searchResults.length > 0 && (
        <div className="absolute top-full left-0 right-0 mt-2 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg max-h-96 overflow-y-auto z-10">
          <div className="p-2">
            <div className="text-xs text-gray-500 dark:text-gray-400 mb-2">
              找到 {searchResults.length} 个结果
            </div>
            {searchResults.map((result, index) => (
              <button
                key={result.setting.id}
                onClick={() => handleResultClick(result)}
                className="w-full text-left p-3 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
              >
                <div className="flex items-start justify-between">
                  <div className="flex-1">
                    <div className="font-medium text-gray-900 dark:text-white">
                      {highlightMatch(result.setting.name, inputValue)}
                    </div>
                    <div className="text-sm text-gray-600 dark:text-gray-400 mt-1">
                      {highlightMatch(result.setting.description, inputValue)}
                    </div>
                    <div className="flex items-center mt-2 space-x-2">
                      <span className="text-xs px-2 py-1 bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-400 rounded">
                        {getCategoryName(result.setting.category)}
                      </span>
                      <span className="text-xs text-gray-500 dark:text-gray-500">
                        匹配: {getMatchTypeName(result.matchType)}
                      </span>
                    </div>
                  </div>
                </div>
              </button>
            ))}
          </div>
        </div>
      )}

      {/* 无结果提示 */}
      {inputValue && searchResults.length === 0 && (
        <div className="absolute top-full left-0 right-0 mt-2 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg p-4 z-10">
          <div className="text-center text-gray-500 dark:text-gray-400">
            <Search className="w-8 h-8 mx-auto mb-2 opacity-50" />
            <div>未找到匹配的设置项</div>
            <div className="text-sm mt-1">尝试使用不同的关键词</div>
          </div>
        </div>
      )}
    </div>
  );
};

// 获取分类名称
const getCategoryName = (category: SettingsCategory): string => {
  const names = {
    [SettingsCategory.Editor]: '编辑器',
    [SettingsCategory.Appearance]: '外观',
    [SettingsCategory.Keyboard]: '快捷键',
    [SettingsCategory.Files]: '文件',
    [SettingsCategory.Extensions]: '扩展',
    [SettingsCategory.Advanced]: '高级'
  };
  return names[category] || category;
};

// 获取匹配类型名称
const getMatchTypeName = (matchType: 'name' | 'description' | 'tag'): string => {
  const names = {
    name: '名称',
    description: '描述',
    tag: '标签'
  };
  return names[matchType] || matchType;
};
